package com.deercrowing.takeaway.service.impl;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.deercrowing.takeaway.common.constant.MessageConstant;
import com.deercrowing.takeaway.common.constant.StatusConstant;
import com.deercrowing.takeaway.common.exception.BusinessException;
import com.deercrowing.takeaway.context.BaseContext;
import com.deercrowing.takeaway.dao.CategoriesMapper;
import com.deercrowing.takeaway.dao.DishesMapper;
import com.deercrowing.takeaway.dao.SetmealsMapper;
import com.deercrowing.takeaway.entity.CategoriesEntity;
import com.deercrowing.takeaway.service.CategoriesService;
import com.deercrowing.takeaway.vo.CategoriesPageVO;
import com.deercrowing.takeaway.vo.CategoriesVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 分类表(Categories)表服务实现类
 *
 * @author guoyongxiang
 * @since 2024-07-10 15:09:05
 */
@Service
@Slf4j
public class CategoriesServiceImpl extends ServiceImpl<CategoriesMapper, CategoriesEntity> implements CategoriesService {

    @Autowired
    CategoriesMapper categoriesMapper;

    @Autowired
    DishesMapper dishesMapper;

    @Autowired
    SetmealsMapper setmealsMapper;

    @Override
    public void categoryStatusUpdate(Short status, Integer id) {
        if (ObjectUtils.isEmpty(categoriesMapper.selectById(id))){
            throw new BusinessException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        categoriesMapper.updateByStatus(status, id);
    }

    @Override
    public void deleteConnectRelates(List<Integer> ids) {
        for (int index = 0; index < ids.size(); index++){
            int count = dishesMapper.countIndex(ids.get(index));
            if (count > 0){
                ids.remove(index);
                throw new BusinessException(MessageConstant.CATEGORY_BE_RELATED_BY_DISH);
            }

            count = setmealsMapper.countIndex(ids.get(index));
            if (count > 0){
                ids.remove(index);
                throw new BusinessException(MessageConstant.CATEGORY_BE_RELATED_BY_SETMEAL);
            }
        }
    }

    @Override
    public void deleteConnectRelates(Integer id) {
        int count = dishesMapper.countIndex(id);
        if (count > 0){
            throw new BusinessException(MessageConstant.CATEGORY_BE_RELATED_BY_DISH);
        }

        count = setmealsMapper.countIndex(id);
        if (count > 0){
            throw new BusinessException(MessageConstant.CATEGORY_BE_RELATED_BY_SETMEAL);
        }

        CategoriesEntity categoriesEntity = categoriesMapper.selectById(id);
        if (StatusConstant.ENABLE == categoriesEntity.getStatus()){
            throw new BusinessException(MessageConstant.CATEGORY_ON_SALE);
        }

        categoriesMapper.deleteById(id);
    }

    @Override
    public List<CategoriesEntity> searchAllCategory() {
        List<CategoriesEntity> categoriesEntityList = categoriesMapper.selectListByStatus();

        if (ObjectUtils.isEmpty(categoriesEntityList))
        {
            throw new BusinessException("当前分类为空，请添加分类");
        }

        return categoriesEntityList;
    }

    @Override
    public IPage<CategoriesVO> searchByCondition(CategoriesPageVO categoriesPageVO) {
        int page = categoriesPageVO.getPage() == null ? 1 : categoriesPageVO.getPage();
        int pageSize = categoriesPageVO.getPageSize() == null ? 10 : categoriesPageVO.getPageSize();

        Integer limit = (page-1) * pageSize;
        categoriesPageVO.setPage(limit);
        categoriesPageVO.setPageSize(pageSize);

        List<CategoriesEntity> categoriesEntityList = categoriesMapper.selectListByCondition(categoriesPageVO);

        if (categoriesEntityList.size() < 0){
            throw new BusinessException(MessageConstant.CATEGORY_NOT_FOUND);
        }

        List<CategoriesVO> categoriesVOList = categoriesEntityList.stream().
                map(source -> new CategoriesVO(
                        source.getId(),
                        source.getType(),
                        source.getName(),
                        source.getSort(),
                        source.getStatus(),
                        source.getUpdateTime()))
                .collect(Collectors.toList());

        Integer count = categoriesMapper.countCategoryNum(categoriesPageVO);
        IPage<CategoriesVO> entityIPage = new Page<>(page,pageSize);
        entityIPage.setTotal(count);
        entityIPage.setRecords(categoriesVOList);
        return entityIPage;
    }

    @Override
    public CategoriesVO searchById(Integer id) {
        CategoriesEntity categoriesEntity = categoriesMapper.selectById(id);
        CategoriesVO categoriesVO = new CategoriesVO();
        BeanUtils.copyProperties(categoriesEntity,categoriesVO);
        return categoriesVO;
    }

    @Override
    public List<CategoriesVO> searchByType(Short type) {
        List<CategoriesEntity> categoriesEntityList = categoriesMapper.selectListByType(type);

        if (categoriesEntityList.size() < 0 || categoriesEntityList == null){
            throw new BusinessException(MessageConstant.CATEGORY_NOT_FOUND);
        }

        List<CategoriesVO> categoriesVOList = categoriesEntityList.stream().
                map(source -> new CategoriesVO(
                        source.getId(),
                        source.getType(),
                        source.getName(),
                        source.getSort(),
                        source.getStatus(),
                        source.getUpdateTime()))
                .collect(Collectors.toList());
        return categoriesVOList;
    }

    @Override
    public void updateInfoToDB(Integer id, CategoriesVO categoriesVO) {
        CategoriesEntity entity = categoriesMapper.selectById(id);
        if (ObjectUtils.isEmpty(entity) || ObjectUtils.isEmpty(categoriesVO))
        {
            throw new BusinessException(MessageConstant.CATEGORY_NOT_FOUND);
        }

        // 对比数据库中是否存在相同名称分类，传入ID，name
        List<CategoriesEntity> cgList = categoriesMapper.selectList();
        for (CategoriesEntity categorie : cgList){
            if (categoriesVO.getName().equals(categorie.getName()) && id != categorie.getId()){
                throw new BusinessException(MessageConstant.TYPENAME_ALREADY_EXISTS);
            }
        }

        // 根据ID插入数据
        entity.setName(categoriesVO.getName())
              .setSort(categoriesVO.getSort())
              .setUpdateTime(LocalDateTime.now())
              .setUpdateEmployee(BaseContext.getCurrentId().intValue())
              .updateById();
    }

    @Override
    public void insertInfoToDB(CategoriesVO categoriesVO) {
        // 判断数据库中是否有重复名称
        List<CategoriesEntity> cgList = categoriesMapper.selectList();
        for (CategoriesEntity categorie : cgList){
            if (categoriesVO.getName().equals(categorie.getName())){
                throw new BusinessException(MessageConstant.TYPENAME_ALREADY_EXISTS);
            }
        }

        // 视图类转换实体类
        CategoriesEntity entity = new CategoriesEntity();
        BeanUtils.copyProperties(categoriesVO,entity);

        // 插入数据
        entity.setId(0)
              .setStatus(StatusConstant.DISABLE)
              .setCreateTime(LocalDateTime.now())
              .setUpdateTime(LocalDateTime.now())
              .setCreateEmployee(BaseContext.getCurrentId().intValue())
              .setUpdateEmployee(BaseContext.getCurrentId().intValue())
              .insert();
    }
}

